/**
 * Created by pkd on 2017/3/13.
 */
var aliApiHelper = module.exports;

var express = require('express');
var taoClient = require('../libs/tao_sdk');
var request = require('request');
var TaoApi = taoClient.ApiClient;
// 这个是高昌建个人的淘客站APP
// var atbClient = new TaoApi({
//     'appkey': '23535521',
//     'appsecret': '1e109fc3f42d55b758de981d94b1cc46',
//     'REST_URL': 'http://gw.api.taobao.com/router/rest'
// });

var taoApi = [
    // {
    //     'appkey': '23855312',
    //     'appsecret': '420e649ab04d0ed178ed0efd7cfcde3c',
    //     'REST_URL': 'http://gw.api.taobao.com/router/rest'
    // },
    // {
    //     'appkey': '24285293',
    //     'appsecret': '54b8a69b326f870d4f691c74a7e505d6',
    //     'REST_URL': 'http://gw.api.taobao.com/router/rest'
    // },
    // {
    //     'appkey': '24285803',
    //     'appsecret': 'c0d5fdbcab48eddd6956e16e452cea68',
    //     'REST_URL': 'http://gw.api.taobao.com/router/rest'
    // },
    {
        'appkey': '24283958',
        'appsecret': 'd1820bc6ee825d7fcb49caf1c6b37b35',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24285293',
        'appsecret': '54b8a69b326f870d4f691c74a7e505d6',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24284739',
        'appsecret': '40a69b0efc36d3858999d5a27356d46b',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24285051',
        'appsecret': 'e73f1b228e0911c0f9b4750952270695',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    // {
    //     'appkey': '24284496',
    //     'appsecret': 'd7f8a61cf1c5454d4c7f5724f15743c0',
    //     'REST_URL': 'http://gw.api.taobao.com/router/rest'
    // },
    // {
    //     'appkey': '24285048',
    //     'appsecret': '420e649ab04d0ed178ed0efd7cfcde3c',
    //     'REST_URL': 'http://gw.api.taobao.com/router/rest'
    // },
    {
        'appkey': '24285222',
        'appsecret': '7b922bbb49753e6a57f38456f3846f92',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24285009',
        'appsecret': '64ba0ea87c668871e451272804521131',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24284821',
        'appsecret': '1813ccf65b2b06fa254f7ef3fe77608d',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24285008',
        'appsecret': '5f24bbefd03a70eb4d804d005aa1b5a0',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24284298',
        'appsecret': '4c2175c4678d67cd70eb9e8b52a02d14',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24283776',
        'appsecret': 'db0d93be26b1e617630bb691b29da585',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24283772',
        'appsecret': 'd73488fec16d77125b870e943e67325d',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24283578',
        'appsecret': 'a460bd91fd51e48689d02c28827ee1c6',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    },
    {
        'appkey': '24283958',
        'appsecret': 'd1820bc6ee825d7fcb49caf1c6b37b35',
        'REST_URL': 'http://gw.api.taobao.com/router/rest'
    }
];


/**
 * 获取商品简要信息：
 * @iids 数组。里面包含1-20个淘宝商品的id，即auctionId
 * @cb回调，第一个是错误，第二个是商品信息数组。包含：id, 名称，活动价，30天销量
 *
 aliApiHelper.getGoodsInfoSimple([534381139076, 545232681272], function (err, rsp) {
        console.log(err);
        console.log(rsp);
    });
 */
aliApiHelper.getGoodsInfoSimple = function(iids, cb){
    var atbClient = new TaoApi(taoApi[Math.round(Math.random()* (taoApi.length -1))]);
    if(!(iids instanceof Array)){
        cb('input only support array!');
        return;
    }
    var strIIds = iids.join(',');
    atbClient.execute('taobao.tbk.item.info.get', {
        'fields':'num_iid,title,zk_final_price,volume,seller_id,nick',
        'platform':'1',
        'num_iids':strIIds
    }, function(error, response) {
        if (!error){
            if(!response || !response.results){
                cb('淘宝API返回数据错误！');
                return;
            }
            cb(null, response.results.n_tbk_item, strIIds);
        }
        else{
            cb(error);
        }
    })
}

function getGoodsInfoQQHD(auctionIdOrUrl, cb) {
    if (!isNaN(auctionIdOrUrl)) {
        auctionIdOrUrl = 'https://item.taobao.com/item.htm?id=' + auctionIdOrUrl;
    }
    var urlGet = 'http://pub.alimama.com/items/channel/qqhd.json?channel=qqhd&perPageSize=40&q=';
    urlGet += encodeURIComponent(auctionIdOrUrl);
    getGoodsInfo(urlGet, cb);
}

function getGoodsInfoNormal(auctionIdOrUrl, cb) {
    if (!isNaN(auctionIdOrUrl)) {
        auctionIdOrUrl = 'https://item.taobao.com/item.htm?id=' + auctionIdOrUrl;
    }
    var urlGet = 'http://pub.alimama.com/items/search.json?q=';
    urlGet += encodeURIComponent(auctionIdOrUrl);
    getGoodsInfo(urlGet, cb);
}

function getGoodsInfo(url, cb) {
    if (!isNaN(url)){
        url = 'https://item.taobao.com/item.htm?id=' + url;
    }
    var urlGet = 'http://pub.alimama.com/items/channel/qqhd.json?channel=qqhd&perPageSize=40&q=';
    urlGet += encodeURIComponent(url);

    var options = {
        url : urlGet,
        headers:{
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400'
        }
    };
    request(options, function (error, response, body) {

        if (error || response.statusCode != 200 || !body) {
            cb('取商品失败！');
            return;
        }
        try {
            if (!body || body.length < 2 || '{['.indexOf(body.substr(0, 1)) < 0 ) {
                cb('取商品失败');
                return;
            }
            var rsp = JSON.parse(body);

            if(!rsp || !rsp.ok || !rsp.data){
                cb('取商品失败');
                return;
            }
            if(!rsp.data.pageList || rsp.data.pageList.length <= 0){
                console.log('取商品失败');
                return;
            }
            rsp.data.pageList.forEach(function (g) {    // 计算最高佣金
                g.maxTkRate = 0;
                var tks = g.tkSpecialCampaignIdRateMap;
                if(tks){
                    for(var cid in tks){
                        var thisTkRate = parseFloat(tks[cid]);
                        if(g.maxTkRate < thisTkRate){
                            g.maxTkRate = thisTkRate;
                        }
                    }
                }
                if(g.pictUrl.indexOf('//') == 0) g.pictUrl = 'http:' + g.pictUrl;
            })
            cb(null, rsp.data.pageList[0]);
        }
        catch (e) {
            cb('取商品失败');
        }
    });
}

//

aliApiHelper.analysisCouponUrl = function(data, cb) {
    var atbClient = new TaoApi(taoApi[Math.round(Math.random()* (taoApi.length -1))]);
    var param = {};
    if(data.me) param.me = data.me;
    if(data.item_id) param.item_id = data.item_id;
    if(data.activity_id) param.activity_id = data.activity_id;
    atbClient.execute('taobao.tbk.coupon.get',param, function(error, response) {
        if (!error){
            cb(null, response);
        }
        else{
            cb(error);
        }
    })
}

